package com.zzxx.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzxx.wechat.adpater.ArcteryxSkuAdapter;
import com.zzxx.wechat.common.arcteryx.ColourOption;
import com.zzxx.wechat.common.arcteryx.SizeOption;
import com.zzxx.wechat.common.arcteryx.Variant;
import com.zzxx.wechat.common.vo.ArcteryxSpuInfoVo;
import com.zzxx.wechat.dao.ArcteryxLinkDao;
import com.zzxx.wechat.dao.ArcteryxSkuDao;
import com.zzxx.wechat.dao.ArcteryxSpuDao;
import com.zzxx.wechat.dao.UserAttentionDao;
import com.zzxx.wechat.entity.ArcteryxLink;
import com.zzxx.wechat.entity.ArcteryxSku;
import com.zzxx.wechat.entity.ArcteryxSpu;
import com.zzxx.wechat.exception.BusinessException;
import com.zzxx.wechat.service.ArcteryxService;
import com.zzxx.wechat.util.HttpProxyClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@Primary
public class ArcteryxServiceImpl implements ArcteryxService {


    @Autowired
    private ArcteryxSkuDao arcteryxSkuDao;
    @Autowired
    private ArcteryxSpuDao arcteryxSpuDao;
    @Autowired
    private UserAttentionDao userAttentionDao;
    @Resource
    private ArcteryxLinkDao arcteryxLinkDao;
    @Resource
    private HttpProxyClient httpProxyClient;

    public List<ArcteryxSku> analysisUrl(String url) {


        log.info("解析URL传入链接:{}", url);

        String htmlStr = httpProxyClient.doGetIgnoreSsl(url);

        // 使用 Jsoup 解析 HTML
        Document document = Jsoup.parse(htmlStr);
        Elements element = document.select("#__NEXT_DATA__");
        String html = element.html();
        if (StringUtils.isEmpty(html)) {
            log.error("解析URL返回为空,链接:{}", url);
            throw new BusinessException("解析URL返回为空,请确认输入链接正确");
        }
        //  log.info("解析URL返回JSON:{},", html);

        // return analysisProduct(url, html);
        return null;
    }

    public ArcteryxSpuInfoVo analysisProduct(ArcteryxLink arcteryxLink, String html) {

        ArcteryxSpuInfoVo arcteryxSpuInfoVo = new ArcteryxSpuInfoVo();
        JSONObject sourceJSON = JSON.parseObject(html).getJSONObject("props").getJSONObject("pageProps").getJSONObject("product");
        // 颜色，尺码 枚举
        JSONObject colourOptions = sourceJSON.getJSONObject("colourOptions");
        JSONObject sizeOptions = sourceJSON.getJSONObject("sizeOptions");

        Map<String, SizeOption> sizeOptionMap = sizeOptions.getJSONArray("options").toJavaList(SizeOption.class).stream().collect(Collectors.toMap(SizeOption::getValue, v -> v));
        Map<String, ColourOption> colourOptionMap = colourOptions.getJSONArray("options").toJavaList(ColourOption.class).stream().collect(Collectors.toMap(ColourOption::getValue, v -> v));
        // Sku对象
        List<Variant> variantList = sourceJSON.getJSONArray("variants").toJavaList(Variant.class);


        //SPU 对象
        ArcteryxSpu arcteryxSpu = buildArcteryxSpu(sourceJSON);
        arcteryxSpuInfoVo.setSpuId(arcteryxSpu.getSpuId());
        arcteryxSpuInfoVo.setAnalyticsName(arcteryxSpu.getAnalyticsName());

        List<String> skuIdList = variantList.stream().map(Variant::getId).collect(Collectors.toList());
/*
        Map<String, ArcteryxSku> oldArcterySkuMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(skuIdList)) {
            oldArcterySkuMap = arcteryxSkuDao.queryBySkuIds(arcteryxLink.getUrl(), skuIdList).stream().collect(Collectors.toMap(ArcteryxSku::getSkuId, v -> v));
        }
*/

        List<ArcteryxSku> arcteryxSkuList = new ArrayList<>();
        for (Variant variant : variantList) {
            ArcteryxSku arcteryxSku = new ArcteryxSku();
            BeanUtils.copyProperties(variant, arcteryxSku);
            arcteryxSku.setId(null);
            arcteryxSku.setSpuId(arcteryxLink.getSpuId());
            arcteryxSku.setSkuId(variant.getId());
            arcteryxSku.setSkuName(colourOptionMap.get(arcteryxSku.getColourId()).getImage().getLabel());
            arcteryxSku.setSkuImage(colourOptionMap.get(arcteryxSku.getColourId()).getImage().getUrl());
            arcteryxSku.setSizeLabel(sizeOptionMap.get(arcteryxSku.getSizeId()).getLabel());
            arcteryxSku.setColourLabel(colourOptionMap.get(arcteryxSku.getColourId()).getLabel());
            arcteryxSku.setLinkId(arcteryxLink.getId());
            arcteryxSku.setUrl(arcteryxLink.getUrl());
         /*   if (oldArcterySkuMap.get(arcteryxSku.getSkuId()) != null) {
                arcteryxSku.setId(oldArcterySkuMap.get(arcteryxSku.getSkuId()).getId());
            }*/
            arcteryxSkuList.add(arcteryxSku);
        }
        //  arcteryxSkuDao.insertOrUpdateBatch(arcteryxSkuList);
        arcteryxSpuInfoVo.setArcteryxSkuVoList(ArcteryxSkuAdapter.arcteryxSku2Vos(arcteryxSkuList));
        return arcteryxSpuInfoVo;
    }

    private ArcteryxSpu buildArcteryxSpu(JSONObject sourceJSON) {
        ArcteryxSpu acteryxSpu = new ArcteryxSpu();

        acteryxSpu.setSpuId(sourceJSON.getString("id"));
        acteryxSpu.setSpuName(sourceJSON.getString("name"));
        acteryxSpu.setAnalyticsName(sourceJSON.getString("analyticsName"));
        acteryxSpu.setPrice(sourceJSON.getBigDecimal("price"));
        acteryxSpu.setDiscountPrice(sourceJSON.getBigDecimal("discountPrice"));
        acteryxSpu.setMinPrice(sourceJSON.getBigDecimal("minPrice"));
        acteryxSpu.setMinDiscountPrice(sourceJSON.getBigDecimal("minDiscountPrice"));
        return acteryxSpu;
    }
}